package zhuyun.code.launcheractivity.view.widget

import android.content.Context
import android.os.Handler
import android.util.AttributeSet
import android.util.Log
import android.view.LayoutInflater
import android.view.MotionEvent
import android.view.View
import android.view.ViewGroup
import android.widget.FrameLayout
import android.widget.ImageView
import android.widget.LinearLayout
import androidx.viewpager.widget.PagerAdapter
import androidx.viewpager.widget.ViewPager
import kotlinx.android.synthetic.main.banner_layout.view.*
import zhuyun.code.launcheractivity.R
import zhuyun.code.launcheractivity.model.Constants
import zhuyun.code.launcheractivity.view.widget.component.BannerScroller
import zhuyun.code.launcheractivity.view.widget.component.ImageLoaderInferface

/**
 * @author: Administrator
 * @date: 2021/11/19
 */
class Banner(private val mContext: Context, private val attrs:AttributeSet, private val defStyle:Int):
    FrameLayout(mContext,attrs,defStyle),ViewPager.OnPageChangeListener {
    constructor(mContext: Context,attrs: AttributeSet?):this(mContext,attrs!!,0)
    constructor(mContext: Context):this(mContext,null)
    private val tag = "Banner"
    private var mIndicatorWidth:Int = 0
    private var mIndicatorHeight:Int = 0
    private var mIndicatorMargin:Int = 0
    private var mIndicatorSelectedResId:Int = 0
    private var mIndicatorUnselectedResId:Int = 0
    private var scaleType:Int = 1
    private var delayTime:Int = 0
    private var scrollTime:Int = 0
    private var bannerBackgroundImage:Int = 0
    private var indicatorSize = mContext.resources.displayMetrics.widthPixels/80

    init {
        handleTypedArray(mContext,attrs)
        LayoutInflater.from(context).inflate(R.layout.banner_layout,this,true)
        initViewPagerScroll()
    }

    private fun handleTypedArray(mContext: Context,attrs: AttributeSet){
        if(attrs == null){
            return
        }
        val typedArray = mContext.obtainStyledAttributes(attrs, R.styleable.Banner)
        mIndicatorWidth = typedArray.getDimensionPixelSize(R.styleable.Banner_indicator_width,indicatorSize)
        mIndicatorHeight = typedArray.getDimensionPixelSize(R.styleable.Banner_indicator_height,indicatorSize)
        mIndicatorMargin = typedArray.getDimensionPixelSize(R.styleable.Banner_indicator_margin,Constants.PADDING_SIZE)
        mIndicatorSelectedResId = typedArray.getResourceId(R.styleable.Banner_indicator_drawable_selected,R.drawable.gray_radius)
        mIndicatorUnselectedResId = typedArray.getResourceId(R.styleable.Banner_indicator_drawable_unselected,R.drawable.white_radius)
        scaleType = typedArray.getInt(R.styleable.Banner_image_scale_type,scaleType)
        delayTime = typedArray.getInt(R.styleable.Banner_delay_time,Constants.TIME)
        scrollTime = typedArray.getInt(R.styleable.Banner_scroll_time,Constants.DURATION)
        bannerBackgroundImage = typedArray.getResourceId(R.styleable.Banner_banner_default_image,R.drawable.no_banner)
        typedArray.recycle()

    }

    private fun initViewPagerScroll(){
        val field = ViewPager::class.java.getDeclaredField("mScroller")
        field.isAccessible = true
        val scroller = BannerScroller(bannerViewPager.context)
        scroller.mDuration = scrollTime
        field.set(bannerViewPager,scroller)
        circleIndicator.visibility

    }

    private var imageUrls:List<String>? = null
    private var mImageLoader:ImageLoaderInferface<ImageView>? = null
    private var count:Int = 0

    fun setImages(imageUrls:List<String>):Banner{
        this.imageUrls = imageUrls
        return this
    }

    fun setImageLoader(imageLoader:ImageLoaderInferface<ImageView>):Banner{
        this.mImageLoader = imageLoader
        return this
    }

    private fun setScaleType(imageView:ImageView){
        when(scaleType){
            0->{
                imageView.scaleType = ImageView.ScaleType.CENTER
            }
            1->{
                imageView.scaleType = ImageView.ScaleType.CENTER_CROP
            }
            2->{
                imageView.scaleType = ImageView.ScaleType.CENTER_INSIDE
            }
            3->{
                imageView.scaleType = ImageView.ScaleType.FIT_CENTER
            }
            4->{
                imageView.scaleType = ImageView.ScaleType.FIT_END
            }
            5->{
                imageView.scaleType = ImageView.ScaleType.FIT_START
            }
            6->{
                imageView.scaleType = ImageView.ScaleType.FIT_XY
            }
            7->{
                imageView.scaleType = ImageView.ScaleType.MATRIX
            }



        }
    }





    fun start(){
        imageUrls?.let { count = it.size  }
        circleIndicator.visibility = if(count>1) View.VISIBLE else View.GONE
        if(imageUrls == null|| this.imageUrls!!.isEmpty()){
            bannerDefaultImage.visibility = View.VISIBLE
            return
        }
        bannerDefaultImage.visibility = View.GONE
        createIndicator()
        loadImages()
        setData()

    }

    fun setAutoPlay(isAutoPlay:Boolean):Banner{
        this.isAutoPlay = isAutoPlay
        return this
    }

    private var adapter:BannerPagerAdapter? = null
    private var currentItem:Int = 1
    private var isAutoPlay:Boolean = false

    private fun setData(){
        if (adapter == null){
            adapter = BannerPagerAdapter()
        }
        bannerViewPager.adapter = adapter
        bannerViewPager.setOnPageChangeListener(this)
        bannerViewPager.currentItem = currentItem
        if(isAutoPlay){
            startAutoPlay()
        }
    }

    private val mHandler = Handler()
    private fun startAutoPlay(){
        mHandler.removeCallbacks(task)
        mHandler.postDelayed(task,delayTime.toLong())
    }

    private fun stopAutoPlay(){
        mHandler.removeCallbacks(task)
    }

    override fun dispatchTouchEvent(ev: MotionEvent?): Boolean {
        if(isAutoPlay){
            when(ev!!.action){
                MotionEvent.ACTION_UP,MotionEvent.ACTION_CANCEL,MotionEvent.ACTION_OUTSIDE->{
                    startAutoPlay()
                }
                MotionEvent.ACTION_DOWN->{
                    stopAutoPlay()
                }

            }
        }
        return super.dispatchTouchEvent(ev)
    }



    private val task:Runnable by lazy {
        Runnable {
            if (count > 1 && isAutoPlay) {
                currentItem = currentItem % (count + 1) + 1
                if (currentItem == 1) {
                    bannerViewPager.setCurrentItem(currentItem, false)
                    mHandler.post(task)
                } else {
                    bannerViewPager.currentItem = currentItem
                    mHandler.postDelayed(task, delayTime.toLong())
                }
            }
        }
    }

    inner class BannerPagerAdapter:PagerAdapter(){
        override fun isViewFromObject(view: View, `object`: Any): Boolean {
            return view == `object`
        }

        override fun getCount(): Int {
            return imageViews.size
        }

        override fun instantiateItem(container: ViewGroup, position: Int): Any {
            container.addView(imageViews[position])
            return imageViews[position]

        }

        override fun destroyItem(container: ViewGroup, position: Int, `object`: Any) {
            container.removeView(`object` as View)
        }
    }

    private fun toRealPosition(position: Int):Int{
        return (position-1+count)%count
    }





    private val imageViews = mutableListOf<ImageView>()

    private fun loadImages(){
        for(i in 0..count+1){
            var imageView = mImageLoader?.let { it.createImageView(context) }
            if(imageView == null){
                imageView = ImageView(context)
            }
            setScaleType(imageView)
            var url:String? = null
            url = imageUrls?.get(toRealPosition(i))
            imageViews.add(imageView)
            if(mImageLoader!=null){
                mImageLoader?.let { it.displayImage(context,url,imageView) }
            } else {
                Log.e(tag,"请设置images loader")
            }





        }
    }

    private val indicatorImages = mutableListOf<ImageView>()


    private fun createIndicator(){
        indicatorImages.clear()
        circleIndicator.removeAllViews()
        for(i in 0 until count){
            val imageView = ImageView(context)
            imageView.scaleType = ImageView.ScaleType.CENTER_CROP
            if( i == 0){
                imageView.setImageResource(mIndicatorSelectedResId)
            } else {
                imageView.setImageResource(mIndicatorUnselectedResId)
            }
            indicatorImages.add(imageView)
            val params = LinearLayout.LayoutParams(mIndicatorWidth,mIndicatorHeight)
            params.leftMargin = mIndicatorMargin
            params.rightMargin = mIndicatorMargin
            circleIndicator.addView(imageView,params)
        }
    }

    override fun onPageScrollStateChanged(state: Int) {
        when(state){
            0->{
                if(currentItem == 0){
                    bannerViewPager.setCurrentItem(count,false)
                } else if(currentItem == count+1){
                    bannerViewPager.setCurrentItem(1,false)
                }
            }
            1->{
                if(currentItem == 0){
                    bannerViewPager.setCurrentItem(count,false)
                } else if(currentItem == count+1){
                    bannerViewPager.setCurrentItem(1,false)
                }
            }

        }
    }

    private var lastPosition:Int = 0

    override fun onPageScrolled(position: Int, positionOffset: Float, positionOffsetPixels: Int) {
        val i = 0
    }

    override fun onPageSelected(position: Int) {
        currentItem = position
        indicatorImages[(lastPosition-1+count)%count].setImageResource(mIndicatorUnselectedResId)
        indicatorImages[(position-1+count)%count].setImageResource(mIndicatorSelectedResId)
        lastPosition = position

    }


}